package com.tenton.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tenton.MyException.DataNotExist;
import com.tenton.MyException.InsufficientQuantity;
import com.tenton.mapper.*;
import com.tenton.pojo.Commodity;
import com.tenton.pojo.ExCommodity;
import com.tenton.pojo.Stock;
import com.tenton.service.StockService;
import com.tenton.utils.Constants;
import com.tenton.utils.IntegerUtils;
import com.tenton.vo.StockVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Date: 2021/1/9
 * @Author: Tenton
 * @Description:
 */
@Service
public class StockServiceImpl implements StockService {
    @Autowired
    StockMapper stockMapper;
    @Autowired
    CommodityMapper commodityMapper;
    @Autowired
    ExCommodityMapper exCommodityMapper;
    @Autowired
    ImCommodityMapper imCommodityMapper;
    @Autowired
    SalesMapper salesMapper;

    /**
     * 删除库存
     *
     * @param id
     * @return
     */
    @Override
    public void deleteByPrimaryKey(Integer id) {
        if (IntegerUtils.isEmpty(id)) {
            throw new NullPointerException("仓库Id为空");
        } else {
            stockMapper.deleteByPrimaryKey(id);
        }
    }

    /**
     * 获取所有库存信息
     *
     * @param pn
     * @param model
     * @return
     */
    @Override
    public void getAll(Integer pn, ModelMap model) {
        PageHelper.startPage(pn, Constants.PAGE_SIZE);
        List<Stock> stocks = stockMapper.selectAll();
        PageInfo<Stock> pageInfo = new PageInfo<Stock>(stocks);
        model.addAttribute("pageInfo", pageInfo);
    }

    /**
     * 查询库存信息
     *
     * @param id
     * @return
     */
    @Override
    public void selectByPrimaryKey(Integer id, Model model) {
        if (IntegerUtils.isEmpty(id)) {
            throw new NullPointerException("仓库Id为空");
        } else {
            model.addAttribute("stock", stockMapper.selectByPrimaryKey(id));
        }
    }

    @Override
    public Stock selectById(Integer id) {
        if (IntegerUtils.isEmpty(id)) {
            throw new NullPointerException("仓库Id为空");
        } else {
            return stockMapper.selectByPrimaryKey(id);
        }
    }

    @Override
    public void getStock(Integer id, Model model) {
        if (IntegerUtils.isEmpty(id)) {
            throw new NullPointerException("仓库Id为空");
        } else {
            Stock stock = stockMapper.selectByPrimaryKey(id);
            Commodity commodity = commodityMapper.selectByPrimaryKey(stock.getComId());
            stock.setCommodity(commodity);
            model.addAttribute("stock", stock);
        }
    }

    /**
     * 修改库存信息
     *
     * @param stock
     * @param session
     * @return
     */
    @Override
    public void update(Stock stock, HttpSession session) throws DataNotExist {
        if (stock != null) {
            String name = (String) session.getAttribute("name");
            stock.setUpdateName(name);
            Date date = new Date();
            stock.setUpdateTime(date);
            stockMapper.updateByPrimaryKey(stock);
        } else {
            throw new DataNotExist("库存信息为空");
        }
    }

    /**
     * 仓库关联商品
     *
     * @param comId
     * @return
     */
    @Override
    public void StockWithCom(Integer comId, Model model) {
        if (IntegerUtils.isEmpty(comId)) {
            throw new NullPointerException("商品Id为空");
        } else {
            Stock stock = stockMapper.StockWithCom(comId);
            Commodity commodity = commodityMapper.selectByPrimaryKey(comId);
            stock.setCommodity(commodity);
            model.addAttribute("stock", stock);
        }
    }

    /**
     * 仓库关联商品
     *
     * @param comId
     * @return
     */
    @Override
    public Stock stockWithComId(Integer comId) {
        if (IntegerUtils.isEmpty(comId)) {
            throw new NullPointerException("商品Id为空");
        } else {
            return stockMapper.StockWithCom(comId);
        }
    }

    /**
     * 仓库关联商品
     *
     * @param exCommodity
     * @param session
     * @return
     */
    @Override
    public void StockWithComByEntity(ExCommodity exCommodity,HttpSession session) throws InsufficientQuantity, DataNotExist {
        if (exCommodity == null) {
            throw new DataNotExist("退货信息为空");
        } else {
            String name = (String) session.getAttribute("name");
            exCommodity.setCreateName(name);
            Date date = new Date();
            exCommodity.setCreateTime(date);
            exCommodityMapper.insert(exCommodity);
            Stock stock = stockMapper.StockWithCom(exCommodity.getComId());
            //此次退货数量
            int exCommodityNum = exCommodity.getNum();
            //仓库中商品库存
            int stockNum = stock.getNum();
            if (stockNum >= exCommodityNum) {
                stockNum = stockNum - exCommodityNum;
                stock.setNum(stockNum);
                stock.setUpdateName(name);
                stock.setUpdateTime(date);
                stockMapper.updateByPrimaryKey(stock);
            } else {
                throw new InsufficientQuantity("商品库存不足");
            }
        }
    }

    /**
     * 仓库库存
     *
     * @param pn
     * @param model
     * @return
     */
    @Override
    public void StockWithComNum(Integer pn, ModelMap model) {
        PageHelper.startPage(pn, Constants.PAGE_SIZE);
        List<StockVo> vos = new ArrayList<>();
        List<Stock> lowStocks = stockMapper.StockWithComNum();
        this.judgeStock(lowStocks,Constants.STOCK_NUM_LOW,vos);
        List<Stock> muchStocks = stockMapper.StockWithComNumMuch();
        this.judgeStock(muchStocks, Constants.STOCK_NUM_MUCH, vos);
        List<Stock> stocks = stockMapper.selectAll();
        for (Stock stock : stocks) {
            //仓库中商品最后修改的时间（毫秒）
            Date updateTime = stock.getUpdateTime();
            //商品进库后就未做任何操作
            if (updateTime == null){
                updateTime = stock.getCreateTime();
            }
            long timeOld = updateTime.getTime();
            //当前时间（毫秒）
            long timeNow = System.currentTimeMillis();
            //相隔天数大于30天，商品未销售，表明此商品不受欢迎
            long day = (timeNow - timeOld) / (1000 * 60 * 60 * 24);
            if (day > Constants.APART_DAYS){
                StockVo stockVo = new StockVo();
                BeanUtils.copyProperties(stock,stockVo);
                stockVo.setReMarks(Constants.COMMODITY_NOT_WELCOME);
                vos.add(stockVo);
            }
        }
        PageInfo<StockVo> pageInfo = new PageInfo<StockVo>(vos);
        model.addAttribute("pageInfo", pageInfo);
    }

    /**
     * 判断商品库存
     *
     * @param stocks
     //* @param reMarks
     * @param vos
     * @return
     */
    public void judgeStock(List<Stock> stocks, String reMarks, List<StockVo> vos){
        for (Stock stock : stocks) {
            StockVo stockVo = new StockVo();
            BeanUtils.copyProperties(stock,stockVo);
            stockVo.setReMarks(reMarks);
            vos.add(stockVo);
        }
    }

    /**
     * 仓库库存
     *
     * @return
     */
    @Override
    public List<Stock> StockWithNum() {
        return stockMapper.StockWithComNum();
    }

    /**
     * 仓库商品生产日期
     *
     * @param pn
     * @param model
     * @return
     */
    @Override
    public void StockWithComData(Integer pn, ModelMap model) {
        PageHelper.startPage(pn, Constants.PAGE_SIZE);
        List<Stock> stocks = stockMapper.StockWithComData();
        PageInfo<Stock> pageInfo = new PageInfo<Stock>(stocks);
        model.addAttribute("pageInfo", pageInfo);
    }

    /**
     * 仓库商品生产日期
     *
     * @return
     */
    @Override
    public List<Stock> StockWithData() {
        return stockMapper.StockWithComData();
    }

    /**
     * 商品名称模糊查询
     *
     * @param comName
     * @param pn
     * @param model
     * @return
     */
    @Override
    public void getByParams(String comName, Integer pn, ModelMap model) {
        PageHelper.startPage(pn, Constants.PAGE_SIZE);
        List<Stock> stocks = stockMapper.getByParams(comName);
        PageInfo<Stock> pageInfo = new PageInfo<Stock>(stocks);
        model.addAttribute("pageInfo", pageInfo);
    }
}
